﻿
//TAO EMBED WINDOW
function Trailer(link, name) {
    $.Dialog({
        overlay: true,
        shadow: true,
        flat: true,
        icon: '',
        title: name,
        content: '',
        onShow: function (_dialog) {
            var html = [
                '<iframe width="640" height="480" src=' + link + ' frameborder="0" allowfullscreen></iframe>'
            ].join("");

            $.Dialog.content(html);
        }
    });
}




//Load List theater when choose a film-nguyenht
function loadTheaterByFilmId(idOfFilm) {
    $.ajax({
        url: "/Schedule/TheatersByFilm",
        type: "GET",
        data: { filmId: idOfFilm },
        success: function (data) {
            $('#listTheater').html(data);
        }
    });
}

//Load list showtime when choose a theater
function loadShowTimeByTheaterId(idOfTheater, searchScheduleFilmId) {
    var scheduleResult = {};
    scheduleResult.FilmId = searchScheduleFilmId;
    scheduleResult.TheaterId = idOfTheater;

    $.ajax({
        type: "POST",
        url: "/Schedule/ShowTimeOfTheater",
        data: "{scheduleResult:" + JSON.stringify(scheduleResult) + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "HTML",
        success: function (html) {
            $('#listShowTime').html(html);
        }

    });
}

//Load list film when choose theater
function loadFilmByTheaterId(idOfTheater) {
    $.ajax({
        url: "/Schedule/FilmsByTheater",
        type: "GET",
        data: { theaterId: idOfTheater },
        success: function (data) {
            $('#listFilmOfTheater').html(data);
        }
    });
}

//Load list showtime when choose a film
function loadShowTimeByFilmId(idOfFilm, searchScheduleTheaterId) {
    var scheduleResult = {};
    scheduleResult.FilmId = idOfFilm;
    scheduleResult.TheaterId = searchScheduleTheaterId;

    $.ajax({
        type: "POST",
        url: "/Schedule/ShowTimeOfFilm",
        data: "{scheduleResult:" + JSON.stringify(scheduleResult) + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "HTML",
        success: function (html) {
            $('#listShowTimeOfFilm').html(html);
        }
    });
}

//QUAN LI PHONG-nguyenht
//checkAll

//tao phong
function addRowHandlers2() {
    var table = document.getElementById("desk2");
    for (i = 0; i < table.rows.length; i++) {
        for (j = 0; j < table.rows[i].cells.length; j++) {
            var cell = $(table.rows[i].cells[j]);
            //chay ham khi click vao o
            registerOnSeatClicked2(cell);
            validate();
        };
    }
}
function registerOnSeatClicked2(cell) {
    cell.click(function () {
        cell.toggleClass('seat_choose');
        validate(cell);
      });
}

function validate(cell) {
    var chairs = document.getElementsByClassName('seat_choose');
    var veri = parseInt(document.getElementById('txtVeri').value);
    var hori = parseInt(document.getElementById('txtHori').value);
    var ddl = "";
    var pos = "";
    var verimax = 0;
    var character = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for (var j = 0; j < hori; j++) {
        verimax = 0;
        //lay ra chuoi vi tri ghe
        for (var i = 0; i < chairs.length; i++) {
            var current_ddl = document.getElementById(chairs[i].innerText.trim());
            var chairex = chairs[i].innerText.split('', 1).toString();
            if (chairex == character[j]) {
                var des = parseInt(current_ddl.options[current_ddl.selectedIndex].value);
                if (des == 2) { des = 1; }
                if (des == 3) { des = 2; }
                verimax = des + verimax;
                if (verimax <= veri) {
                    pos = chairs[i].innerText + " " + pos;
                    ddl = current_ddl.options[current_ddl.selectedIndex].value + " " + ddl;
                }
                else {
                    alert("Độ dài của ghế quá chiều dài quy định");                    
                    cell.toggleClass('seat_choose');                  
                    return;
                }
            }
        }
    }
    var posTxt = document.getElementById('picked2');
    var ddlTxt = document.getElementById('picked3');
    ddlTxt.innerHTML = ddl;
    posTxt.innerHTML = pos;

}
function createChair() {
    var pos = document.getElementById('picked2').innerText;
    var ddl = document.getElementById('picked3').innerText;
    var Apos = document.getElementById('Apicked2').innerText;
    var roomId;
    
    $('.seat_choose').toggleClass().addClass('seated');
    if (pos != '') {
        jQuery("#overlay").css('display', 'block'); // displaying the overlay
        jQuery("#popup").css('display', 'block'); // displaying the popup
        $.ajax({
            url: "/Room/CreateChairs",
            type: "POST",
            data: { listChair: pos, chairType: ddl, allChairs: Apos },
            success: function (data) {
                document.getElementById('crtTable').disabled = true;
                document.getElementById('crtChair').disabled = true;
                window.location.assign("/Room");
            },
            error: function (data) { alert("Tạo Phòng thất bại"); }
        });
    }
    else (alert('Chưa có ghế nào dc chợn'));
}
//tao bang ghe
function createTable() {
    var hori = parseInt(document.getElementById('txtHori').value);
    var veri = parseInt(document.getElementById('txtVeri').value);
    var maxw = parseInt(document.getElementById('ngang').innerHTML.trim());
    var maxh = parseInt(document.getElementById('doc').innerHTML.trim());

    if (hori <= maxw && veri <= maxh && hori > 0 && veri > 0) {
        jQuery("#overlay").css('display', 'block'); // displaying the overlay
        jQuery("#popup").css('display', 'block'); // displaying the popup
        $.ajax({
            url: "/Room/CreateChairTable",
            type: "GET",
            data: { x: hori, y: veri },

            success: function (data) {

                $('#tableChair').html(data);
                document.getElementById('crtChair').setAttribute('style', 'width:77px;display:normal;vertical-align:top');
                document.getElementById('bor').setAttribute('style', "margin:0 auto;opacity:1");
                var allChairs = document.getElementsByClassName('seat');
                var Addl = "";
                var Apos = "";
                for (var j = 0; j < allChairs.length; j++) {
                    //lay ra chuoi vi tri ghe
                    Apos = allChairs[j].innerText + " " + Apos;
                    var AposTxt = document.getElementById('Apicked2');
                    AposTxt.innerHTML = Apos;
                }

            },
            error: function (data) { alert("Tạo bảng ghế không thành công!"); }
        });
    }
    else { alert("Số dòng và cột phải là 2 số nguyên và nhỏ hơn kích cỡ mặc định của rạp"); }

}
//sua phong
function addRowHandlers3() {
    var table = document.getElementById("desk2");
    for (i = 0; i < table.rows.length; i++) {
        for (j = 0; j < table.rows[i].cells.length; j++) {
            var cell = $(table.rows[i].cells[j]);
            //chay ham khi click vao o
            registerOnSeatClicked3(cell);
            validate2();

        };
    }
}
function registerOnSeatClicked3(cell) {
    cell.click(function () {
        cell.toggleClass('seat_choose');
        validate2(cell);
    });
}
function validate2(cell) {
    var chairs = document.getElementsByClassName('seat_choose');
    var veri = parseInt(document.getElementById('txtVeri').value);
    var hori = parseInt(document.getElementById('txtHori').value);
    var ddl = "";
    var pos = "";
    var verimax = 0;
    var character = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for (var j = 0; j < hori; j++) {
        verimax = 0;
        //lay ra chuoi vi tri ghe
        for (var i = 0; i < chairs.length; i++) {
            var current_ddl = document.getElementById(chairs[i].innerText.trim());
            var chairex = chairs[i].innerText.split('', 1).toString();
            if (chairex == character[j]) {
                var des = parseInt(current_ddl.options[current_ddl.selectedIndex].value);
                if (des == 2) { des = 1; }
                if (des == 3) { des = 2; }
                verimax = des + verimax;
                if (verimax <= veri) {
                    pos = chairs[i].innerText + " " + pos;
                    ddl = current_ddl.options[current_ddl.selectedIndex].value + " " + ddl;
                }
                else {
                    alert("Độ dài của ghế quá chiều dài quy định");
                    cell.toggleClass('seat_choose');
                    return;
                }
            }
        }
    }
    var posTxt = document.getElementById('picked2');
    var ddlTxt = document.getElementById('picked3');
    ddlTxt.innerHTML = ddl;
    posTxt.innerHTML = pos;

}
function editChair() {


    var pos = document.getElementById('picked2').innerText;
    var ddl = document.getElementById('picked3').innerText;
    var roomId = document.getElementById('picked4').innerText;
    $('.seat_choose').toggleClass().addClass('seated');
    jQuery("#overlay").css('display', 'block'); // displaying the overlay
    jQuery("#popup").css('display', 'block'); // displaying the popup
    $.ajax({
        url: "/Room/EditChairs",
        type: "POST",
        data: { id: roomId, listChair: pos, chairType: ddl },
        success: function (data) {
            window.location.assign("/Room");
        },
        error: function (data) { alert("Sửa ghế không thành công!"); }
    });
}
//chuyen trang 
function paymentMethod() {
    document.getElementById('checkSdt').setAttribute("style", "display:none");
    document.getElementById('checkEmail').setAttribute("style", "display:none");
    document.getElementById('checkNull').setAttribute("style", "display:none");
    var valid = true;
    var fn = $("#fn").val();
    var sdt = $("#sdt").val();
    var email = $("#email").val();
    var us = /^[a-zA-Z ÀÁÂÃÈÉÊÌÍÒÓÔÕÙÚĂĐĨŨƠàáâãèéêìíòóôõùúăđĩũơƯĂẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼỀỀỂưăạảấầẩẫậắằẳẵặẹẻẽềềểỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỦỨỪễệỉịọỏốồổỗộớờởỡợụủứừỬỮỰỲỴÝỶỸửữựỳỵỷỹ]{5,50}$/;
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    var reg = /^[0-9]{9,15}$/;
    if (fn == '' || sdt == '' || email == '') { document.getElementById('checkNull').setAttribute("style", "display:normal;color:red;font-size:13px;text-align:left"); valid = false; }
    else {
        if (!us.test(fn.replace(/   /g,''))) { document.getElementById('checkUs').setAttribute("style", "display:normal;color:red;font-size:13px;text-align:left"); valid = false; }
        if (!reg.test(sdt)) { document.getElementById('checkSdt').setAttribute("style", "display:normal;color:red;font-size:13px;text-align:left"); valid = false; }
        if (!re.test(email)) { document.getElementById('checkEmail').setAttribute("style", "display:normal;color:red;font-size:13px;text-align:left") ; valid = false;}
    }
    return valid;
}
//BOOK GHE-nguyenht
///Xu li khi cilick vao 1 o
function registerOnSeatClicked(cell) {
    var max = document.getElementById("maxBook").innerHTML;
    max = parseInt(max);
    cell.click(function () {
        var a = cell.attr("class");
        if (a == "seat seat_choose")
        { cell.toggleClass('seat_choose'); }
        if (a == "seatVip seatVip_choose")
        { cell.toggleClass('seatVip_choose'); }
        if (a == "seatCouple seatCouple_choose")
        { cell.toggleClass('seatCouple_choose'); }

        var chairs = $(".seat_choose, .seatVip_choose, .seatCouple_choose");

        if (chairs.length >= 0 && chairs.length < max) {
            if (a == "seat")
            { cell.toggleClass('seat_choose'); }
            if (a == "seatVip")
            { cell.toggleClass('seatVip_choose'); }
            if (a == "seatCouple")
            { cell.toggleClass('seatCouple_choose'); }

        }
        else { alert('Bạn chỉ được chọn '+max+' ghế 1 lần mua'); }
        HandleChooseChairs();
    });
}
//Xu li khi cac o da chon
function HandleChooseChairs() {
    var max = document.getElementById("maxBook").innerHTML;
    max = parseInt(max);
    var chairs = $(".seat_choose, .seatVip_choose, .seatCouple_choose");
    //xu li 10 ghe dc chon
    if (chairs.length <= max && chairs.length > 0) {
        document.getElementById("muave").disabled = false;
        document.getElementById("muave").setAttribute("class", "button info");
        var pos = "";
        var ticketid = "";
        var totalPrice = 0;
        var chairTypeR, chairType;
        for (var i = 0; i < chairs.length; i++) {
            //lay ra chuoi vi tri ghe
            pos = chairs[i].innerText + " " + pos;
            //lay ra chuoi id vé
            ticketid = chairs[i].children[0].innerText.trim() + " " + ticketid;
            //thanh toan dua tren loai ghe
            chairTypeR = chairs[i].children[1].innerText;
            chairType = $.trim(chairTypeR);
            chairType = parseFloat(chairType);
            totalPrice = chairType + totalPrice;
        }
        totalPrice = totalPrice.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
        //
        var posTxt = document.getElementById('picked');
        var posTxt2 = document.getElementById('ChairPos');
        var ticketIdTxt = document.getElementById('getId');
        var priceTxt = document.getElementById('giaTien');
        posTxt.innerHTML = pos;
        posTxt2.value = pos;
        ticketIdTxt.value = ticketid;
        priceTxt.innerHTML = totalPrice + " VND";

    } else if (chairs.length == 0) {
        document.getElementById("muave").disabled = true;
        document.getElementById("muave").setAttribute("class", "button");
        document.getElementById('picked').innerHTML = "Chưa có ghế được chọn";
        document.getElementById('giaTien').innerHTML = "0 VND";
        document.getElementById('getId').innerHTML = "";

    }

    else { alert("Bạn chỉ được chọn "+max+" ghế 1 lần mua"); }
}
//Xac dinh vi tri tung o
function addRowHandlers() {
    
    document.getElementById("muave").disabled = true;
    var table = document.getElementById("desk");

    for (i = 0; i < table.rows.length; i++) {
        for (j = 0; j < table.rows[i].cells.length; j++) {
            var cell = $(table.rows[i].cells[j]);
            //chay ham khi click vao o
            registerOnSeatClicked(cell);
        };

    }

}
//CHECK TRUNG
function popUp() {
    HandleChooseChairs();
    var listTicketId = document.getElementById('getId').value;

    $.ajax({
        url: "/CheckOut/CheckSameChairs",
        type: "GET",
        data: { listId: listTicketId },
        success: function (data) {
            if (data == "false") {

                document.getElementById('popUp').setAttribute("style", "display:normal");
            }
            else { alert("Ghế đã được chọn, xin vui lòng chọn ghế khác"); location.reload(); }
        },
        error: function (data) {

        }
    });


}
//SUGGEST FILM FOR CUSTOMER AND GUEST
function countCategoryView(cateId) {
    // Check browser support for localStorage
    if (typeof (Storage) !== "undefined") {
        //create it localStorage if FilmTicketBookingSystem localStorage doesn't exist
        if (localStorage.getItem("FilmTicketBookingSystem") == null) {
            //Set default value
            var category = { id: cateId, view: 0 };
            var listCategory = []
            listCategory.push(category);

            //Convert listCategory to JSON -> Save value to localStorage
            localStorage.setItem("FilmTicketBookingSystem", JSON.stringify(listCategory));
        }
            //If exist localStorage FilmTicketBookingSystem, get value to continue count view
        else {
            var listCategoryStr = localStorage.getItem("FilmTicketBookingSystem");
            var listCategory = jQuery.parseJSON(listCategoryStr);
            //Flag to know that found the category need to count
            var isFound = false;
            //If categoryId in localStorage == categoryId of user choosen, add view count into localStorage
            for (var i = 0; i < listCategory.length; i++) {
                if (listCategory[i].id === cateId) {
                    listCategory[i].view++;
                    isFound = true;
                    break;
                }
            }
            //if category isn't in list, add new
            if (!isFound) {
                var category = { id: cateId, view: 1 };
                listCategory.push(category);
            }
            //Modify the localStorage FilmTicketBookingSystem to update the new result
            localStorage.setItem("FilmTicketBookingSystem", JSON.stringify(listCategory));
        }
    }
    else {
        document.getElementById("result").innerHTML = "Xin lỗi! Trình duyệt của bạn không hỗ trợ tính năng gợi ý phim bạn hay xem!";
    }
}

//Get localStorage data
//VuongVT
toDictionary: function getLocalStorageViewResult() {
    var listCategoryStr = localStorage.getItem("FilmTicketBookingSystem");
    var listCategory = jQuery.parseJSON(listCategoryStr);
    return listCategory;
}

//Suggest nearest theater
function setPositionOfUser(lat, long, theaterId1, theaterId2, theaterId3, time1, time2, time3, dis1, dis2, dis3) {
    // Check browser support for localStorage
    if (typeof (Storage) !== "undefined") {
        //create localStorage if NearestTheater localStorage doesn't exist
        if (localStorage.getItem("Position") == null) {
            //Set default value
            var positions = { latitue: lat, longtitue: long };

            var listPosition = []
            listPosition.push(positions);

            //Convert listCategory to JSON -> Save value to localStorage
            localStorage.setItem("Position", JSON.stringify(listPosition));
        }
            //If exist localStorage FilmTicketBookingSystem, get value to continue count view
        else {
            var positionStr = localStorage.getItem("Position");
            var position = jQuery.parseJSON(positionStr);
            localStorage.removeItem("Position");
            //Set new value
            var positions = { latitue: lat, longtitue: long };
            var listPosition = []
            listPosition.push(positions);

            //Modify the localStorage Position to update the new result
            localStorage.setItem("Position", JSON.stringify(listPosition));
        }

        if (localStorage.getItem("NearestTheater") == null) {
            //Set default value
            var timeAndDics1 = time1 + dis1;
            var timeAndDics2 = time2 + dis2;
            var timeAndDics3 = time3 + dis3;
            var nearsTheater1 = { theater: theaterId1, timeanddics: timeAndDics1 };
            var listNearesTheater = []
            listNearesTheater.push(nearsTheater1);
            var nearsTheater2 = { theater: theaterId2, timeanddics: timeAndDics2 };
            listNearesTheater.push(nearsTheater2);
            var nearsTheater3 = { theater: theaterId3, timeanddics: timeAndDics3 };
            listNearesTheater.push(nearsTheater3);

            //Convert listNearesTheater to JSON -> Save value to localStorage
            localStorage.setItem("NearestTheater", JSON.stringify(listNearesTheater));
        }
        else {
            var nearestStr = localStorage.getItem("NearestTheater");
            var nearest = jQuery.parseJSON(nearestStr);
            localStorage.removeItem("NearestTheater");

            //Set new value
            var timeAndDics1 = time1 + dis1;
            var timeAndDics2 = time2 + dis2;
            var timeAndDics3 = time3 + dis3;
            var nearsTheater1 = { theater: theaterId1, timeanddics: timeAndDics1 };
            var listNearesTheater = []
            listNearesTheater.push(nearsTheater1);
            var nearsTheater2 = { theater: theaterId2, timeanddics: timeAndDics2 };
            listNearesTheater.push(nearsTheater2);
            var nearsTheater3 = { theater: theaterId3, timeanddics: timeAndDics3 };
            listNearesTheater.push(nearsTheater3);

            //Convert listNearesTheater to JSON -> Save value to localStorage
            localStorage.setItem("NearestTheater", JSON.stringify(listNearesTheater));
        }
    }
    else {
        document.getElementById("result").innerHTML = "Xin lỗi! Trình duyệt của bạn không hỗ trợ tính năng gợi ý phim bạn hay xem!";
    }
}

//Get localStorage of Position data
//VuongVT
toDictionary: function getPositionLocalStorage() {
    var listPositionStr = localStorage.getItem("Position");
    var listPosition = jQuery.parseJSON(listPositionStr);
    return listPosition;
}

//Get localStorage of NearestTheater data
//VuongVT
toDictionary: function getNearestTheaterListLocalStorage() {
    var listNearestTheaterStr = localStorage.getItem("NearestTheater");
    var listNearestTheater = jQuery.parseJSON(listNearestTheaterStr);
    return listNearestTheater;
}


function checkLogin() {
    var username = $("#username").val();
    var password = $("#password").val();
    $.ajax({
        url: '/AccessPermission/CheckLogin',
        type: 'POST',
        data: { username: username, password: password },
        success: function (response) {
            if (response == "Customer") {
                if (window.location.pathname == "/Home/Announcement" || window.location.pathname == "/Customer/Register" || window.location.pathname == "/Customer/ForgetPassword" || window.location.pathname == "/Home/Index" || window.location.pathname == "/" || window.location.pathname == "/Home") {
                    window.location.href = "/Home/Customer";
                }
                else {
                    window.location.reload();
                }
            } else if (response == "Supplier") {
                window.location.href = "/Admin/SupplierPage";
            } else if (response == "Admin") {
                window.location.href = "/Admin/Index";
            } else if (response == "Staff") {
                window.location.href = "/Admin/StaffPage";
            } else if (response == "Deactive") {
                alert("Tài khoản này đã bị khoá!!!");
            } else {
                alert("Tên đăng nhập hoặc mật khẩu chưa đúng!!!");
            }
        }
    });
}
//Logout-hungph
function LogOut() {
    $.ajax({
        url: '/AccessPermission/LogOut',
        type: 'POST',
        success: function (response) {
            if (response == "Success") {
                window.location.href = "/Home";
            } else {
                alert("Không thể đăng xuất!!!");
            }
        }
    });

}